package com.kgd.news.utils;

import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.util.Map;


public abstract class ApiController extends Controller {

	public static final int PAGE_SIZE = 5;

	public Log log = Log.getLog(ApiController.class);

	public int getPageIndex(){
		return Integer.parseInt(StringUtilsWx.isEmpty(getPara("pageIndex")) ? "1": getPara("pageIndex"));
	}

	/**
	 * 获取项目请求根路�?
	 * 
	 * @return
	 */
	protected String getCxt() {
		return getAttr(Constants.request_cxt);
	}

	protected String getFileVituralPath(String path){
		return getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort()
				+ "/admin/upload/" + path;
	}

	protected String getFileUploadPath(UploadFile file) {
		return FileHelper.getFileHostUrl(getRequest(), file);
	}

	protected String getUploadPath() {
		return getRequest().getScheme() + "://" + getRequest().getServerName()+ ":" + getRequest().getServerPort();
	}
	
	/**
	 * 获取当前用户id
	 * 
	 * @return
	 */
	protected String getCUserIds() {
		return getAttr(Constants.request_cUserIds);
	}

	/**
	 * 获取当前用户
	 * 
	 * @return

	protected SysUser getSessionUser() {
		return getSessionAttr(Constants.request_cUser);
	}

	
	protected void cacheUser(SysUser user) {
		setSessionAttr(Constants.request_cUser, user);
	}
*/
	/**
	 * 获取ParamMap
	 * 
	 * @return
	 */
	protected Map<String, String> getParamMap() {
		return getAttr(Constants.request_paramMap);
	}

	/**
	 * 添加值到ParamMap
	 * 
	 * @return
	 */
	protected void addToParamMap(String key, String value) {
		Map<String, String> map = getAttr(Constants.request_paramMap);
		map.put(key, value);
	}

	/**
	 * 重写renderJson，避免出现IE8下出现下载弹出框
	 */
	@Override
	public void renderJson(Object object) {
		String userAgent = getRequest().getHeader("User-Agent");
		if(StringUtilsWx.isEmpty(userAgent)){
			super.renderJson(object);
		}else if (userAgent.toLowerCase().indexOf("msie") != -1) {
			render(new JsonRender(object).forIE());
		} else {
			super.renderJson(object);
		}
	}

	/**
	 * 解决IE8下下载失败的问题
	 */
	@Override
	public void renderFile(String file) {
		String userAgent = getRequest().getHeader("User-Agent");
		if (userAgent.toLowerCase().indexOf("msie") != -1) {
			getResponse().reset();
		}
		super.renderFile(file);
	}

	/**
	 * 解决IE8下下载失败的问题
	 */
	@Override
	public void renderFile(File file) {
		String userAgent = getRequest().getHeader("User-Agent");
		if (userAgent.toLowerCase().indexOf("msie") != -1) {
			getResponse().reset();
		}
		super.renderFile(file);
	}

}
